package com.turing.common.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.turing.common.spring.SpringApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FdfsUtils {

    private static FastFileStorageClient fdfsClient = SpringApplicationContext.getBean(FastFileStorageClient.class);

    public static String uploadFile(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String name = file.getName();
            String fileExt = name.substring(name.lastIndexOf(".") + 1);
            StorePath storePath = fdfsClient.uploadFile(fileInputStream, fileInputStream.available(), fileExt, null);
            return storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String uploadMultipartFile(MultipartFile multipartFile) {
        try  {
            String name = multipartFile.getOriginalFilename();
            assert name != null;
            String fileExt = name.substring(name.lastIndexOf(".") + 1);
            StorePath storePath = fdfsClient.uploadFile(multipartFile.getInputStream(), multipartFile.getInputStream().available(), fileExt, null);
            return storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String uploadBytes(String data) {

        InputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
        try {

            StorePath storePath = fdfsClient.uploadFile(inputStream,inputStream.available(),"json",null);
            return storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }

    public static String uploadBytesToDFS(byte [] bytes,String fileExt){
        try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
            StorePath storePath = fdfsClient.uploadFile(inputStream,inputStream.available(),fileExt,null);
            return storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void delete_file(String storagePath){
        int result=-1;
        try {
            fdfsClient.deleteFile(storagePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
